package bma.common.netty.webserver.common;

import bma.common.langutil.ai.stack.AIStack;
import bma.common.langutil.core.VPath;
import bma.common.netty.webserver.RequestContext;
import bma.common.netty.webserver.RequestDispatcher;
import bma.common.netty.webserver.RequestProcessor;

public class RequestDispatcherVPath extends RequestDispatcher {

	final org.slf4j.Logger log = org.slf4j.LoggerFactory
			.getLogger(RequestDispatcherVPath.class);

	private String path;
	private VPath vpath;
	private RequestProcessor processor;

	public RequestDispatcherVPath() {
		super();
	}

	public RequestDispatcherVPath(String path, RequestProcessor p) {
		super();
		setPath(path);
		this.processor = p;
	}

	public RequestProcessor getProcessor() {
		return processor;
	}

	public void setProcessor(RequestProcessor processor) {
		this.processor = processor;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
		this.vpath = VPath.create(path);
	}

	@Override
	public boolean dispatch(AIStack<Boolean> stack, RequestContext ctx)
			throws Exception {
		String path = ctx.getPath();
		if (this.path != null && path.startsWith(this.path)) {
			String npath = VPath.create(path).parse().subpath(this.vpath, true)
					.toString();
			if (log.isDebugEnabled()) {
				log.debug("match {}, dispatch {}", this.path, npath);
			}
			ctx.setPath(npath);
			if (dispatchOrProcess(stack, processor, ctx)) {
				return true;				
			}
			ctx.setPath(path);
		}
		return false;
	}

}
